//
//  YQImagePickerManager.m
//  industry
//
//  Created by 王雅强 on 2021/1/26.
//  Copyright © 2021 Haier. All rights reserved.
//

#import "YQImagePickerManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <TZImagePickerController/TZImagePickerController.h>

typedef void (^ImageCompletion)(UIImage * cropImage);
@interface YQImagePickerManager ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, weak) UIViewController *topvc;
@property (nonatomic, copy) ImageCompletion imageCompletion;

@end

@implementation YQImagePickerManager

+ (YQImagePickerManager *)sharedInstance {
    static YQImagePickerManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [YQImagePickerManager new];
    });
    return instance;
}

-(void)cameraTypeCropWithTopVc:(UIViewController *)vc photo:(void (^)(UIImage * cropImage)) completion{
    if (!vc) return;
    if (![self authCameraAndPhotoLibrary]) return ;
    self.topvc = vc;
    self.imageCompletion = completion;
    [self pushImagePickerControllerWith:vc];
    
   
}

-(void)photoTypeCropWithTopVc:(UIViewController *) vc photo:(void (^)(UIImage * cropImage)) completion{
    self.topvc = vc;
    self.imageCompletion = completion;
    [self pushImagePickerController:vc];
    
    
}

-(void)pushImagePickerController:(UIViewController *)vc{
    
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.sortAscendingByModificationDate = NO;
    imagePickerVc.allowCrop = YES;
    NSInteger left = 30;
    NSInteger widthHeight = SCREEN_WIDTH - 2 * left;
    NSInteger top = (SCREEN_HEIGHT - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    imagePickerVc.scaleAspectFillCrop = NO;
    
    WEAKSELF
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.imageCompletion(photos.firstObject);
    }];
    
    [imagePickerVc setImagePickerControllerDidCancelHandle:^{
//                 responseCallbackBlock(@{@"result_code":@(NO)});
    }];
    [self.topvc presentViewController:imagePickerVc animated:YES completion:nil];
}

-(BOOL)authCameraAndPhotoLibrary{
    UIViewController *vc = self.currentTopController;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [vc presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self authCameraAndPhotoLibrary];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [vc presentViewController:alertController animated:YES completion:nil];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self authCameraAndPhotoLibrary];
        }];
    } else {
        return YES;
    }
    return NO;
    
}


// 调用相机
- (void)pushImagePickerControllerWith:(UIViewController *)vc {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];

        [mediaTypes addObject:(NSString *)kUTTypeImage];
        
    
        _imagePickerVc.mediaTypes = mediaTypes;
        
        [vc presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
    
}

#pragma mark - ============== UIImagePickerControllerDelegate ==============
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    WEAKSELF
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
        
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image meta:meta location:nil completion:^(PHAsset *asset, NSError *error){
            [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                    weakSelf.imageCompletion(image);
                    }];
               
                imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
                imagePicker.allowPickingVideo = NO;
                imagePicker.allowPickingGif = NO;
                imagePicker.allowPickingImage = YES;
                imagePicker.sortAscendingByModificationDate = NO;
                imagePicker.allowCrop = YES;
                NSInteger left = 30;
                NSInteger widthHeight = SCREEN_WIDTH - 2 * left;
                NSInteger top = (SCREEN_HEIGHT - widthHeight) / 2;
                imagePicker.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
                imagePicker.scaleAspectFillCrop = NO;
                [weakSelf.topvc presentViewController:imagePicker animated:YES completion:nil];
              
            }
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (UIImagePickerController *)imagePickerVc {
    UIViewController *vc = self.currentTopController;
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = vc.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = vc.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        
        tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
        BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}





@end
